import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import http from '@/helper/request'
import {
    constRouter,
    creatAsyncRouter
} from './router'
Vue.use(VueRouter)

const router = new VueRouter({
    routes: constRouter
})
var path = location.hash.replace('#', '')
router.beforeEach(async (to, from, next) => {
    if (to.path === '/login') {
        next()
        document.getElementById('pageWaiting').style.display = 'none'
    } else {
        var menus = store.state.menus
        if (menus) {
            next()
        } else {
            var token = localStorage.getItem('apptoken')
            if (token) {
                try {
                    var { data } = await http.get('/user/info')
                    document.getElementById('pageWaiting').style.display = 'none'
                    store.commit('setUserInfo', data.user)
                    var asyncRouter = creatAsyncRouter(data.menus)
                    router.addRoutes(asyncRouter)
                    next(path)
                } catch (error) {
                    next('/login')
                }
            } else {
                next(`/login?url=${encodeURIComponent(to.path)}`)
            }
        }
    }
})

export default router
